<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blogs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blogs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blogs/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blogs/images/apple-touch-icon.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/blogs/images/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/blogs/images/favicon-16x16.png?v=5.1.3">


  <link rel="mask-icon" href="/blogs/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="Node.js," />










<meta name="description" content="Express脚手架与路由模块化1.Express脚手架 安装express脚手架，全局安装  1npm install express-generator -g   使用脚手架命令生成一个项目  假如我要生成一个叫myServer的项目 express --view&#x3D;ejs 项目包名 1express --view&#x3D;ejs myServer  此时，就用命令行生成一个项目   接下来按照目录来">
<meta property="og:type" content="article">
<meta property="og:title" content="express脚手架与路由模块化">
<meta property="og:url" content="https://louchaoyy.gitee.io/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/index.html">
<meta property="og:site_name" content="Chao&#39;s blog">
<meta property="og:description" content="Express脚手架与路由模块化1.Express脚手架 安装express脚手架，全局安装  1npm install express-generator -g   使用脚手架命令生成一个项目  假如我要生成一个叫myServer的项目 express --view&#x3D;ejs 项目包名 1express --view&#x3D;ejs myServer  此时，就用命令行生成一个项目   接下来按照目录来">
<meta property="og:locale">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic4.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic5.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic6.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic7.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic8.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic9.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic10.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic11.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic12.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic13.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic14.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic15.png">
<meta property="article:published_time" content="2022-04-29T13:06:48.000Z">
<meta property="article:modified_time" content="2022-04-30T10:51:08.026Z">
<meta property="article:author" content="Chaoyxy">
<meta property="article:tag" content="Node.js">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://louchaoyy.gitee.io/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic4.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://louchaoyy.gitee.io/blogs/2022/04/29/express脚手架与路由模块化/"/>





  <title>express脚手架与路由模块化 | Chao's blog</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blogs/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Chao's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blogs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blogs/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blogs/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://louchaoyy.gitee.io/blogs/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blogs/images/cat.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Chao's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">express脚手架与路由模块化</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2022-04-29T21:06:48+08:00">
                2022-04-29
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2022/04/29/express脚手架与路由模块化/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Express脚手架与路由模块化"><a href="#Express脚手架与路由模块化" class="headerlink" title="Express脚手架与路由模块化"></a>Express脚手架与路由模块化</h1><h2 id="1-Express脚手架"><a href="#1-Express脚手架" class="headerlink" title="1.Express脚手架"></a>1.Express脚手架</h2><ul>
<li>安装express脚手架，全局安装</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install express-generator -g</span><br></pre></td></tr></table></figure>

<ul>
<li>使用脚手架命令生成一个项目</li>
</ul>
<p><strong>假如我要生成一个叫<code>myServer</code>的项目</strong></p>
<p><code>express --view=ejs 项目包名</code></p>
<figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">express -<span class="literal">-view</span>=ejs myServer</span><br></pre></td></tr></table></figure>

<p>此时，就用命令行生成一个项目</p>


<p>接下来按照目录来</p>


<ul>
<li>进入到刚生成的项目里面</li>
</ul>
<figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">cd</span> myServer</span><br></pre></td></tr></table></figure>

<ul>
<li>安装所有项目依赖</li>
</ul>
<figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install</span><br></pre></td></tr></table></figure>



<ul>
<li>启动项目</li>
</ul>
<figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm <span class="built_in">start</span></span><br></pre></td></tr></table></figure>

<img src="/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic4.png" class title="启动项目">

<p>项目默认运行在3000端口，浏览器输入<code>http://localhost:3000</code>查看</p>
<img src="/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic5.png" class title="启动项目的首页">

<span id="more"></span>

<p>运行的文件脚本是<code>bin</code></p>
<ul>
<li>所以修改为使用<strong>nodemon的热启动</strong></li>
</ul>
<p><strong>热启动（重点）</strong></p>
<p>进入到顶级目录下的<code>package.json</code>里面</p>
<p>将script节点下的start的值改为<strong>nodemon ./bin/www</strong></p>
<p>如下：</p>
<img src="/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic6.png" class title="将script节点下的start的值改为nodemon .&#x2F;bin&#x2F;www">

<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;name&quot;</span>: <span class="string">&quot;myserver&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;version&quot;</span>: <span class="string">&quot;0.0.0&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;private&quot;</span>: <span class="literal">true</span>,</span><br><span class="line">  <span class="attr">&quot;scripts&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;start&quot;</span>: <span class="string">&quot;nodemon  ./bin/www&quot;</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">&quot;dependencies&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;cookie-parser&quot;</span>: <span class="string">&quot;~1.4.4&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;debug&quot;</span>: <span class="string">&quot;~2.6.9&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;ejs&quot;</span>: <span class="string">&quot;~2.6.1&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;express&quot;</span>: <span class="string">&quot;~4.16.1&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;http-errors&quot;</span>: <span class="string">&quot;~1.6.3&quot;</span>,</span><br><span class="line">    <span class="attr">&quot;morgan&quot;</span>: <span class="string">&quot;~1.9.1&quot;</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>修改文件后，自动启动，如下</p>
<img src="/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic7.png" class title="修改文件后自动刷新">

<ul>
<li>修改默认端口号</li>
</ul>
<p>由于该脚手架构建的项目，默认端口是3000，因此如果端口冲突了，我们需要更改端口号，步骤如下</p>
<p>首先进入app.js，添加如下代码</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">process.env.PORT = <span class="number">8888</span>;</span><br></pre></td></tr></table></figure>

<img src="/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic8.png" class title="修改默认端口号">

<ul>
<li>项目结构如下图</li>
</ul>
<img src="/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic9.png" class title="项目结构">

<h2 id="2-路由模块化"><a href="#2-路由模块化" class="headerlink" title="2.路由模块化"></a>2.路由模块化</h2><p>由于在4月25日的博客中，我们通过路由的模块化，减少了app.js的体积以及负荷，这里我们打算再继续精简一下，进一步解耦合，进一步增加内聚性，向高内聚，低耦合发展。</p>
<p>在路由模块，我们使用路由把请求都抽离出去了，但是我们还有很多逻辑，依然在router里面去进行，这样的坏处是虽然降低了app.js的负荷，但是router的负担却进一步加重了，因为我们把路由和逻辑处理放在一起了。那么假如我们把路由处理函数单独抽离出来，让路由专心的去处理自己的下一跳，而不去管逻辑处理，这样，就自己干自己的事情，进一步解耦合，岂不美哉？</p>
<p>说干就干。</p>
<p>我们在根目录下创建一个router_handler目录，这个目录用于处理所有的路由处理函数，我们把处理函数同样分模块进行分类，首先是<code>user.js</code>文件，这个模块里面都是处理跟用户相关的逻辑，比如登录等。</p>
<p>如下所示：</p>
<img src="/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic10.png" class title="模块化">

<p>在app.js中，我们为user模块路由添加的前缀是’/users’</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">app.use(<span class="string">&#x27;/users&#x27;</span>, usersRouter);</span><br></pre></td></tr></table></figure>

<p>在routes/users.js路由模块中，我们的登录模块就不需要处理逻辑了，直接负责转发就行，如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//routes/users.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> router = express.Router();</span><br><span class="line"><span class="keyword">const</span> userRouter = <span class="built_in">require</span>(<span class="string">&#x27;../router_handler/user&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">/* GET users listing. */</span></span><br><span class="line">router.get(<span class="string">&#x27;/&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res, next</span>) </span>&#123;</span><br><span class="line">  res.send(<span class="string">&#x27;respond with a resource&#x27;</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 登录模块</span></span><br><span class="line">router.post(<span class="string">&#x27;/login&#x27;</span>,userRouter.login);</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = router;</span><br></pre></td></tr></table></figure>

<p>这里，我们导入了路由处理函数<code>../router_handler/user</code>的内容，在路由处理函数模块内，我们需要向外暴露相关的模块</p>
<p>那么在路由处理函数中，我们又是怎么去做的呢？下面请看</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//这就是登录模块的路由处理函数</span></span><br><span class="line"><span class="built_in">exports</span>.login = <span class="function">(<span class="params">req,res</span>)=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(req.body);</span><br><span class="line">    res.send(&#123;</span><br><span class="line">        <span class="attr">status</span>:<span class="number">200</span>,</span><br><span class="line">        <span class="attr">msg</span>:<span class="string">&quot;请求成功！&quot;</span></span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这就是登录模块的路由处理函数，当然，我们这里需要更详细的做，今天由于时间原因我只是简单举个例子而已。</p>
<p>那么这么拆分了之后，我们还能正常请求数据吗？答案是肯定的，如下</p>
<img src="/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic11.png" class title="postman请求数据">

<p>后端响应</p>
<img src="/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic12.png" class title="后端响应">



<h2 id="3-如何模块化中间件？"><a href="#3-如何模块化中间件？" class="headerlink" title="3.如何模块化中间件？"></a>3.如何模块化中间件？</h2><p>看到路由能模块化，那中间件能模块化吗？</p>
<p>绝对能，因为路由其实也是一种中间件，那么康康我是怎么模块化中间件的。</p>
<p>首先，在项目顶级目录下创建一个middleware的目录，该目录下创建middleUsers.js的文件，关于users的中间件处理，今后往这儿写</p>
<ul>
<li>这里写什么呢？同样的道理，我们在这个中间件处理模块写两个中间件，分别为请求体添加两个属性，一个reach属性，一个islogin属性，并且分别打印两句话，如下：</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * middleUers.js</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> </span>req  请求对象</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> </span>res  响应对象</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> </span>next 下一步执行回调函数</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="built_in">exports</span>.mw1 = <span class="function">(<span class="params">req,res,next</span>)=&gt;</span>&#123;</span><br><span class="line">    req.body.reach = <span class="literal">true</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;我是第1个中间件,我添加了一个reach的属性&quot;</span>);</span><br><span class="line">    next();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">exports</span>.mw2 = <span class="function">(<span class="params">req,res,next</span>)=&gt;</span>&#123;</span><br><span class="line">    req.body.islogin = <span class="literal">true</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;我是第2个中间件,我添加了一个islogin的属性&quot;</span>);</span><br><span class="line">    next();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>在路由模块中，我们需要使用这俩中间件，因此我们需要引入这个模块</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> router = express.Router();</span><br><span class="line"><span class="comment">//引入路由模块和中间件模块</span></span><br><span class="line"><span class="keyword">const</span> userRouter = <span class="built_in">require</span>(<span class="string">&#x27;../router_handler/user&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> middleUsers = <span class="built_in">require</span>(<span class="string">&#x27;../middleware/middleUsers&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">/* GET users listing. */</span></span><br><span class="line">router.get(<span class="string">&#x27;/&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res, next</span>) </span>&#123;</span><br><span class="line">  res.send(<span class="string">&#x27;respond with a resource&#x27;</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// hello接口</span></span><br><span class="line">router.get(<span class="string">&#x27;/hello&#x27;</span>,<span class="function">(<span class="params">req,res</span>)=&gt;</span>&#123;</span><br><span class="line">  res.send(&#123;</span><br><span class="line">    <span class="attr">status</span>:<span class="number">200</span>,</span><br><span class="line">    <span class="attr">msg</span>:<span class="string">&quot;hello hi&quot;</span>,</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// 登录模块</span></span><br><span class="line"><span class="comment">//使用俩中间件</span></span><br><span class="line">router.post(<span class="string">&#x27;/login&#x27;</span>,middleUsers.mw1,middleUsers.mw2,userRouter.login);</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = router;</span><br></pre></td></tr></table></figure>

<ul>
<li>在postman中进行测试</li>
</ul>
<img src="/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic13.png" class title="postman进行测试">

<p>后台响应结果</p>
<img src="/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic14.png" class title="后台响应结果">

<p>很显然，这两个中间件函数已经执行了，响应也没问题。</p>
<p>对于一次普通的请求来说，函数执行过程和顺序大概是这样的，以上面登录为例，从reuest发起请求到response响应请求全过程如下：</p>
<img src="/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/pic15.png" class title="请求函数执行流转图">

<p>好了，路由模块化和中间件模块化今天先到这里！！！</p>
<p>感冒了，想早点休息了</p>
<p><strong>项目代码放在gitee了，该项目会不断更新，如有需要可以自取，不客气！！！</strong></p>
<p><strong>gitee地址如下：</strong></p>
<p><a target="_blank" rel="noopener" href="https://gitee.com/louchaoyy/my-server">https://gitee.com/louchaoyy/my-server</a></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="http://chaoyxy.cn/data/User/admin/home/desktop/images/alipay.jpg" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="http://chaoyxy.cn/data/User/admin/home/desktop/images/wechatpay.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blogs/tags/Node-js/" rel="tag"># Node.js</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blogs/2022/04/28/Express%E4%B8%AD%E7%9A%84JWT%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81/" rel="next" title="Express中的JWT身份认证">
                <i class="fa fa-chevron-left"></i> Express中的JWT身份认证
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blogs/2022/05/01/Express%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96/" rel="prev" title="Express代码优化">
                Express代码优化 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a target="_blank" rel="noopener" href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blogs/images/cat.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blogs/archives">
              
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blogs/tags/index.html">
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/louchaoyy" target="_blank" title="Gitee">
                      
                        <i class="fa fa-fw fa-gitee"></i>Gitee</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="louchao@louchaoyy.cn" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96"><span class="nav-number">1.</span> <span class="nav-text">Express脚手架与路由模块化</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-Express%E8%84%9A%E6%89%8B%E6%9E%B6"><span class="nav-number">1.1.</span> <span class="nav-text">1.Express脚手架</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96"><span class="nav-number">1.2.</span> <span class="nav-text">2.路由模块化</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E5%A6%82%E4%BD%95%E6%A8%A1%E5%9D%97%E5%8C%96%E4%B8%AD%E9%97%B4%E4%BB%B6%EF%BC%9F"><span class="nav-number">1.3.</span> <span class="nav-text">3.如何模块化中间件？</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Chaoyxy</span>

  
</div>

<span id="busuanzi_container_site_pv">
    本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<!--

  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.3</div>
-->




        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/blogs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/blogs/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/blogs/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/blogs/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/blogs/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/blogs/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/blogs/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/blogs/js/src/bootstrap.js?v=5.1.3"></script>



  


  

    
      <script id="dsq-count-scr" src="https://Chaoyxy.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'https://louchaoyy.gitee.io/blogs/2022/04/29/express%E8%84%9A%E6%89%8B%E6%9E%B6%E4%B8%8E%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%9D%97%E5%8C%96/';
          this.page.identifier = '2022/04/29/express脚手架与路由模块化/';
          this.page.title = 'express脚手架与路由模块化';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://Chaoyxy.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  





  

  

  

  
  

  

  

  

</body>
</html>
